<?php
namespace app\home\controller;
use think\Db;
use think\captcha\Captcha;
use think\Loader;
class Login extends \think\Controller{
    public function login(){
        if(isset($_POST['put'])){
            $tell=$_POST['tell'];
            $pwd=$_POST['pwd'];
            $res=db('user')->where('tell',$tell)->find();         
            if($tell==$res['tell']&&$pwd==$res['pwd']){
                session('name',$res['name']);
                session('id',$res['id']);
                $this->success('登录成功!','home/homepage/homepage');
            }
            else {
                $this->error('登录失败');
            }
        }
        // return $this->fetch('login');//继承基类的控制器

        $appid="3911964253";
        $redirect_uri="http://wx.weiyinstudio.com?backurl=http://www.oppo.org/index.php/home/login/weibo?";
        $wb_url="https://api.weibo.com/oauth2/authorize?client_id={$appid}&response_type=code&redirect_uri={$redirect_uri}";
        $this->assign('wb_url',$wb_url);
        return view('login');
        
    }
    public function weibo(){
        $code=input('get.code');
        $appid="3911964253";
        $client_secret="7ebbd60b716a6163e8108d9e12109de8";
        $redirect_uri="http://wx.weiyinstudio.com?backurl=http://http://www.oppo.org/index.php/home/login/weibo?";
        $wb_url="https://api.weibo.com/oauth2/access_token?client_id={$appid}&client_secret={$client_secret}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
        $token=post($wb_url,array());
        $token=json_decode($token,true);
        if($token==false){
            $this->error('access_token获取失败!');
        }
        // var_dump($token);
        // echo "<pre>";

        $access_token=$token['access_token'];
        $uid=$token['uid'];
        $wb_url2="https://api.weibo.com/2/users/show.json?access_token={$access_token}&uid={$uid}";
        $info=get($wb_url2,array());
        if($token==false){
            $this->error('用户信息获取失败!');
        }
        $info=json_decode($info,true);
        // var_dump($info);

        session('info',$info);
        $res=db('user')->where("weibo_uid={$info['id']}")->find();  

        // $id=$info['id'];
        // $res=Db::name('user')->where('weibo_uid',$id)->find();  
        if(empty($res)){
            // $_SESSION['user_id']=$res['id'];
            // $this->redirect('home/login/bind');
            $this->success('请绑定手机号码','home/login/bind');
        }else{
            // $_SESSION['weibo_uid']=$id;
            // $_SESSION['user_id']=$res['id'];
            // echo "123";
            session('weibo_uid',$res['weibo_uid']);
            session('user_id',$res['id']);
            $this->success('登录成功!','home/homepage/homepage');
        }
    }
    public function bind(){
        $this->redirect('home/bind/bind');
        
        // $info=session('info');
        // $data=[
        //     'tell'=>$_SESSION['tell'],
        //     'weibo_uid'=>$info['id'],
        // ];
    }
}